// components/img-upload/index.js
let AV = require('../../sdk/av-core-min')
Component({
    behaviors: ['wx://form-field'], //让本组件表现为表单控件
    /**
     * 组件的属性列表
     */
    properties: {
        avatar:String
    },

    /**
     * 组件的初始数据
     */
    data: {
        imgUrl:''
    },

    /**
     * 组件的方法列表
     */
    methods: {
        handleUpload(){
            wx.chooseMedia({
                mediaType:['image'],
                success:async(res)=>{
                    console.log(res);
                    let {tempFilePath} = res.tempFiles[0] //获取本地图片临时路径
                    let response = await new AV.File('miniprograme.png', {
                        blob: {
                            uri: tempFilePath,
                        },
                    }).save() // 上传
                    console.log(response);
                    let {url} = response.attributes //获取在线图片链接
                    this.setData({
                        imgUrl:url,
                        value:url //将图片链接提供给表单
                    })
                }
            })
        }
    },
    lifetimes:{
        ready(){ //避免用户没有上传新头像，导致的旧头像丢失
            console.log('默认头像',this.properties);
            let {avatar} = this.properties
            if(avatar){
                this.setData({value:avatar})
            }
        }
    }
})
